<?php
/*
 * Created on Oct 2, 2010
 * Createb by Le Duy Khanh
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
class Counter extends DataObject{
	static $db = array (
		'Hit'=>'Int',
	);
	public function requireDefaultRecords() {
		parent :: requireDefaultRecords();
		if (!DataObject :: get_one("Counter")) {
			$counter = new Counter();
			$counter->Hit = "1";
			$counter->write();
		}
	}
	public function getCounter($id,$bol=true){
		if($bol)
		{
			$dotset=DataObject::get_by_id('Counter',$id);
			$hit=$dotset->Hit;
			$hit++;
			$SQL_addedTax = Convert :: raw2sql($id);
			DB :: query("UPDATE `Counter` SET Hit = '$hit' WHERE ID = $id");
		}
		return DataObject::get_by_id('Counter',$id);;
	}
	public function CountHit() {
		$dotset=new DataObjectSet();
		$ip = Session :: get('Counter');
		if($ip){
			if($ip!= Counter :: getIP()){
				Session :: set('Counter',Counter :: getIP());
				$dotset = Counter :: getCounter(1,true);
			}else{
				$dotset = Counter :: getCounter(1,false);
			}
		}else{
			Session :: set('Counter',Counter :: getIP());
			$dotset = Counter :: getCounter(1,true);
		}
		$base_url = 'utility/';
		$default_style = '57chevy';
		$default_ext = 'gif';
		$count_unique = 0;
		$unique_hours = 24;
		$min_digits = 5;
		$style = $default_style;
		$style_dir = 'styles/'.$style.'/';
		$ext = $default_ext;

		$count=$dotset->Hit;
		if ($min_digits > 0) {
			$count = sprintf('%0'.$min_digits.'s', $count);
		}
		return $count;
	}
	function CountVisitors() {
		global $dbfile, $expire;
		$dbfile = BASE_PATH."/utility/visitors.db";  // path to data file
		$expire = 100; // average time in seconds to consider someone online before removing from the list

		if(!file_exists($dbfile)) {
			die("Error: Data file " . $dbfile . " NOT FOUND!");
		}

		if(!is_writable($dbfile)) {
			die("Error: Data file " . $dbfile . " is NOT writable! Please CHMOD it to 666!");
		}
		$cur_ip = Counter :: getIP();
		$cur_time = time();
		$dbary_new = array();
		$dbary = unserialize(file_get_contents($dbfile));
		if(is_array($dbary)) {
			while(list($user_ip, $user_time) = each($dbary)) {
				if(($user_ip != $cur_ip) && (($user_time + $expire) > $cur_time)) {
					Counter :: getCounter(1,true);
				}
			}
		}
		$dbary_new[$cur_ip] = $cur_time; // add record for current user
		$fp = fopen($dbfile, "w");
		fputs($fp, serialize($dbary_new));
		fclose($fp);
		//$out = sprintf(" %03d", count($dbary_new)); // format the result to display 3 digits with leading 0's
		$out=Counter :: CountHit();
		return $out;
	}

	function getIP() {
		if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		elseif(isset($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR'];
		else $ip = "0";
		return $ip;
	}
}
?>
